<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import ProductionLine from '../components/ProductionLine.vue';

// 从localStorage获取设置，如果没有则使用默认值
const loadBackendSettings = () => {
  const settings = localStorage.getItem('wabtec_settings');
  if (settings) {
    try {
      const parsedSettings = JSON.parse(settings);
      return {
        host: parsedSettings.host || 'localhost',
        port: parsedSettings.port || '8000'
      };
    } catch (error) {
      console.error('解析localStorage设置失败:', error);
    }
  }
  // 如果localStorage中没有设置，使用默认值
  return {
    host: 'localhost',
    port: '8000'
  };
};

const backendSettings = loadBackendSettings();
const backend = `${backendSettings.host}:${backendSettings.port}`;

// 接收路由传递的参数
const props = defineProps({
  lineGroup: {
    type: String,
    default: '1-3'
  }
});

// 使用ref存储当前日期和时间
const currentDate = ref('');
const productionLines = ref([]);
const loading = ref(false);
const error = ref(null);
let websocket = null; // WebSocket连接实例



// 根据lineGroup获取对应的产线组
const getLineRangeByGroup = (group) => {
  // 直接返回两条产线
  return ['HVAC CP', 'Door Wiring']
};

// 创建产线中英文名称映射
const lineNameMapping = {
  'HVAC CP': '',
  'Door Wiring': ''
};

// 更新时间的函数
const updateDateTime = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  currentDate.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  
  // 检查是否到达自动刷新时间（0:00:03）
  if (hours === '00' && minutes === '00' && seconds === '03') {
    console.log('到达自动刷新时间：00:00:03，执行刷新操作');
    refreshData();
  }
};

// 刷新数据的函数
const refreshData = () => {
  console.log('执行数据刷新操作...');
  fetchProductionData();
  // initWebSocket();
};

// 模拟到达指定时间的测试函数
const simulateRefreshTime = () => {
  console.log('模拟到达刷新时间，执行刷新操作');
  refreshData();
};

// 存储原始数据
const originalProductionData = ref([]);

// 从API获取生产线数据
const fetchProductionData = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    const response = await fetch(`http://${backend}/v1/getProductionInfo`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    });
    
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }
    
    const data = await response.json();
    
    if (data.message && data.Production_info) {
      // 保存原始数据
      originalProductionData.value = [...data.Production_info];
      
      // 处理数据并更新视图
      processAndUpdateProductionLines();
    } else {
      throw new Error(data.message || '未知错误：返回数据格式不正确');
    }
  } catch (err) {
    console.error('获取生产线数据失败:', err);
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};

// 处理原始数据并更新视图
const processAndUpdateProductionLines = () => {
  // 合并相同产线的数据
  const mergedLines = [];
  const lineMap = new Map();
  
  // 按产线名称分组
  originalProductionData.value.forEach(line => {
    if (!lineMap.has(line.lineName)) {
      lineMap.set(line.lineName, []);
    }
    lineMap.get(line.lineName).push(line);
  });
  
  // 处理每个产线组的数据
  processProductionLines(lineMap, mergedLines);

  // 获取当前选择的产线组
  const lineNames = getLineRangeByGroup(props.lineGroup);

  // 根据产线名称筛选要显示的产线
  const filteredLines = mergedLines.filter(line => lineNames.includes(line.lineName));
  
  // 根据产线组中的顺序进行排序
  productionLines.value = filteredLines.sort((a, b) => {
    // 获取在lineNames数组中的索引位置
    const indexA = lineNames.indexOf(a.lineName);
    const indexB = lineNames.indexOf(b.lineName);
    // 按照在lineNames中的顺序排序
    return indexA - indexB;
  }).map(line => {
    // 为每条产线添加中文名称
    const chineseName = lineNameMapping[line.lineName] || '';
    return {
      ...line,
      lineName: chineseName ? `${chineseName} ${line.lineName}` : line.lineName
    };
  });
  
  console.log(`成功更新产线组 ${props.lineGroup} 的数据:`, productionLines.value);
};

// 处理产线数据的辅助函数
const processProductionLines = (lineMap, mergedLines) => {
  lineMap.forEach((lines, lineName) => {
    if (lines.length === 1) {
      // 计算完成率
      calculateCompletionRates(lines[0], lines[0].weeklyPlan.dataItems[0].value
      , lines[0].weeklyPlan.dataItems[1].value, lines[0].dailyPlan.dataItems[1].value
      , lines[0].dailyPlan.dataItems[2].value);
      // 如果只有一条数据，直接添加
      mergedLines.push(lines[0]);
    } else {
      // 如果有多条数据，需要合并
      const mergedLine = createEmptyMergedLine(lines[0].lineId, lineName);
      
      // 合并数据
      let totalWeeklyPlan = 0;
      let totalWeeklyActual = 0;
      let totalDailyPlan = 0;
      let totalDailyActual = 0;
      let projectNames = [];
      
      // 处理每条产线数据
      lines.forEach(line => {
        // 合并周计划数据
        line.weeklyPlan.dataItems.forEach(item => {
          if (item.label === '计划数量 Plan Qty.') {
            totalWeeklyPlan += item.value;
            mergedLine.weeklyPlan.dataItems[0].value = totalWeeklyPlan;
          } else if (item.label === '实际产量 Actual Qty.') {
            totalWeeklyActual += item.value;
            mergedLine.weeklyPlan.dataItems[1].value = totalWeeklyActual;
          }
        });
        
        // 合并日计划数据
        line.dailyPlan.dataItems.forEach(item => {
          if (item.label === '项目 Project') {
            if (item.value && !projectNames.includes(item.value)) {
              projectNames.push(item.value);
            }
          } else if (item.label === '计划数量 Plan Qty.') {
            totalDailyPlan += item.value;
            mergedLine.dailyPlan.dataItems[1].value = totalDailyPlan;
          } else if (item.label === '实际产量 Actual Qty.') {
            totalDailyActual += item.value;
            mergedLine.dailyPlan.dataItems[2].value = totalDailyActual;
          }
        });
      });
      
      // 设置项目名称
      mergedLine.dailyPlan.dataItems[0].value = projectNames.join(' / ');
      
      // 计算完成率
      calculateCompletionRates(mergedLine, totalWeeklyPlan, totalWeeklyActual, totalDailyPlan, totalDailyActual);
      
      mergedLines.push(mergedLine);
    }
  });
};

// 创建空的合并产线对象
const createEmptyMergedLine = (lineId, lineName) => {
  return {
    lineId,
    lineName,
    weeklyPlan: {
      dataItems: [
        { label: '计划数量 Plan Qty.', value: 0 },
        { label: '实际产量 Actual Qty.', value: 0 }
      ],
      completionRate: 0
    },
    dailyPlan: {
      dataItems: [
        { label: '项目 Project', value: '' },
        { label: '计划数量 Plan Qty.', value: 0 },
        { label: '实际产量 Actual Qty.', value: 0 }
      ],
      completionRate: 0
    }
  };
};

// 计算完成率
const calculateCompletionRates = (line, totalWeeklyPlan, totalWeeklyActual, totalDailyPlan, totalDailyActual) => {
  console.log(`开始计算产线 ${line.lineId} (${line.lineName}) 的完成率`);
  console.log(`周计划数据: 计划=${totalWeeklyPlan}, 实际=${totalWeeklyActual}`);
  console.log(`日计划数据: 计划=${totalDailyPlan}, 实际=${totalDailyActual}`);
  
  // 计算周计划完成率
  if (totalWeeklyPlan > 0) {
    const oldRate = line.weeklyPlan.completionRate;
    line.weeklyPlan.completionRate = Math.min(Math.round((totalWeeklyActual / totalWeeklyPlan) * 100),100);
    
  
  } else {
    // 当计划数量为0时，显示完成率为100%
    const oldRate = line.weeklyPlan.completionRate;
    line.weeklyPlan.completionRate = 100;

  }
  
  // 计算日计划完成率
  if (totalDailyPlan > 0) {
    const oldRate = line.dailyPlan.completionRate;
    line.dailyPlan.completionRate = Math.min(Math.round((totalDailyActual / totalDailyPlan) * 100),100);
  } else {
    // 当计划数量为0时，显示完成率为100%
    const oldRate = line.dailyPlan.completionRate;
    line.dailyPlan.completionRate = 100;
  }
  
  console.log(`产线 ${line.lineId} (${line.lineName}) 完成率计算完毕`);
};

let reconnectInterval = 1000; // 初始重连间隔（1秒）
let maxReconnectInterval = 30000; // 最大重连间隔（30秒）

// 初始化WebSocket连接
const initWebSocket = () => {
  console.log('开始初始化WebSocket连接...');
  
  // 关闭已存在的连接
  if (websocket) {
    console.log('关闭现有WebSocket连接');
    websocket.close();
  }
  
  // 创建新的WebSocket连接
  console.log(`创建新的WebSocket连接: ws://${backend}/ws/updateActualQty`);
  websocket = new WebSocket(`ws://${backend}/ws/updateActualQty`);
  
  // 连接建立时的回调
  websocket.onopen = () => {
    console.log('WebSocket连接已成功建立');
    reconnectInterval = 1000; // 重置重连间隔
  };
  
  // 接收消息的回调
  websocket.onmessage = (event) => {
    try {
      // 打印原始消息
      console.log('收到WebSocket消息:', event.data);
      
      const data = JSON.parse(event.data);
      
      // 打印解析后的消息
      console.log('解析后的WebSocket消息:', data);
      
      if (data) {
        const { line_id, line_name, dailyActualQty, weeklyActualQty } = data;
        
        // 打印提取的关键数据
        console.log('产线更新数据:', {
          产线ID: line_id,
          产线名称: line_name,
          日实际产量: dailyActualQty,
          周实际产量: weeklyActualQty
        });
        
        // 更新原始数据中的产量信息，而不是直接更新处理后的数据
        updateOriginalProductionData(line_id, line_name, dailyActualQty, weeklyActualQty);
      }
    } catch (err) {
      console.error('WebSocket消息解析错误:', err);
    }
  };
  
  // 更新原始数据中的产量信息
  const updateOriginalProductionData = (lineId, lineName, dailyActualQty, weeklyActualQty) => {
    console.log(`开始更新原始数据中产线 ${lineId} (${lineName}) 的数据`);
    
    // 查找原始数据中对应的产线记录
    const lineRecords = originalProductionData.value.filter(line => line.lineId === lineId);
    
    if (lineRecords.length > 0) {
      console.log(`找到 ${lineRecords.length} 条产线 ${lineId} 的原始记录`);
      
      // 更新每条记录的产量数据
      lineRecords.forEach(record => {
        // 更新日实际产量
        const dailyActualItem = record.dailyPlan.dataItems.find(item => item.label === '实际产量 Actual Qty.');
        if (dailyActualItem) {
          const oldValue = dailyActualItem.value;
          dailyActualItem.value = dailyActualQty;
          console.log(`原始数据日实际产量更新: ${oldValue} -> ${dailyActualQty}`);
        }
        
        // 更新周实际产量
        const weeklyActualItem = record.weeklyPlan.dataItems.find(item => item.label === '实际产量 Actual Qty.');
        if (weeklyActualItem) {
          const oldValue = weeklyActualItem.value;
          weeklyActualItem.value = weeklyActualQty;
          console.log(`原始数据周实际产量更新: ${oldValue} -> ${weeklyActualQty}`);
        }
      });
      
      // 重新处理数据并更新视图
      processAndUpdateProductionLines();
      console.log('已重新处理数据并更新视图');
    } else {
      console.warn(`未在原始数据中找到ID为 ${lineId} 的产线记录`);
    }
  };
  
  // 连接关闭时的回调
  websocket.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 可以在这里添加重连逻辑
    setTimeout(() => {
      // 增加间隔时间，避免疯狂重连
      reconnectInterval = Math.min(reconnectInterval * 2, maxReconnectInterval);
      connectWebSocket();
    }, reconnectInterval);
  };
  
  // 连接错误时的回调
  websocket.onerror = (error) => {
    console.error('WebSocket连接错误:', error);
    websocket.close(); // 主动关闭以触发 onclose 重连
  };
};

// 定时器引用
let timer = null;

// 监听路由参数变化，重新获取数据
watch(() => props.lineGroup, (newGroup) => {
  console.log(`产线组变更为: ${newGroup}`);
  if (originalProductionData.value.length > 0) {
    // 如果已有数据，直接重新处理
    processAndUpdateProductionLines();
  } else {
    // 否则重新获取数据
    fetchProductionData();
  }
});

// 组件挂载时启动定时器和获取数据
onMounted(() => {
  updateDateTime();
  timer = setInterval(updateDateTime, 1000);
  fetchProductionData();
  initWebSocket(); // 初始化WebSocket连接
});

// 组件卸载时清除定时器和WebSocket连接
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  
  // 关闭WebSocket连接
  if (websocket) {
    websocket.close();
    websocket = null;
  }
});

// 页面可见性变化处理
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    // 页面变为可见时，如果WebSocket未连接则重新连接
    if (!websocket || websocket.readyState !== WebSocket.OPEN) {
      console.log('页面可见，确保WebSocket连接');
      initWebSocket();
    }
  }
  // 移除关闭WebSocket的逻辑，让WebSocket在后台也保持连接
};

// 监听页面可见性变化
onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});
</script>

<template>
  <div class="container">
    <header class="header">
      <img src="../assets/wabtec-logo.png" alt="Wabtec Logo" class="logo">
      <h1 class="title">生产线状态 Production line status</h1>
      <div class="date">{{ currentDate }}</div>
    </header>
    
    <!-- 隐藏导航链接 -->
    <!-- <div class="navigation">
      <router-link to="/lines/1-3" class="nav-link" :class="{ active: props.lineGroup === '1-3' }">产线 1-3</router-link>
      <router-link to="/lines/4-6" class="nav-link" :class="{ active: props.lineGroup === '4-6' }">产线 4-6</router-link>
      <router-link to="/lines/7-9" class="nav-link" :class="{ active: props.lineGroup === '7-9' }">产线 7-9</router-link>
    </div> -->
    
    <div v-if="loading" class="loading">
      数据加载中...
    </div>
    
    <div v-else-if="error" class="error">
      加载失败: {{ error }}
    </div>
    
    <div v-else class="production-lines">
      <ProductionLine 
        v-for="line in productionLines" 
        :key="line.lineId"
        :lineId="line.lineId"
        :lineName="line.lineName"
        :weeklyPlan="line.weeklyPlan"
        :dailyPlan="line.dailyPlan"
      />
    </div>
    
    <!-- 添加测试按钮 -->
    <div class="test-button-container" v-if="false">
      <button @click="simulateRefreshTime" class="test-button">
        测试刷新
      </button>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Arial', 'Microsoft YaHei', sans-serif;
  background-color: #f5f5f5;
}

.container {
  /* max-width: 1200px; */
  margin: 0 auto;
  padding: 8px;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #ddd;
  width: 100%;
}

.logo {
  height: 100px;
}

.title {
  font-size: 50px;
  font-weight: bold;
  text-align: center;
  margin: 0;
}

.date {
  text-align: right;
  font-weight: bold;
  font-size: 25px;
}

.navigation {
  display: flex;
  justify-content: center;
  margin: 10px 0;
  gap: 20px;
}

.nav-link {
  padding: 5px 15px;
  text-decoration: none;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #f0f0f0;
}

.nav-link.active {
  background-color: #0078d4;
  color: white;
  border-color: #0078d4;
}

.production-lines {
  margin-top: 10px;
  width: 100%;
}

.loading, .error {
  text-align: center;
  padding: 20px;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.error {
  color: #f44336;
}

.test-button-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.test-button {
  background-color: #0078d4;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s;
}

.test-button:hover {
  background-color: #005a9e;
}

.test-button:active {
  background-color: #004578;
}
</style>

